package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 自动取消超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void cancelTimeoutOrder(){
        //未支付订单的最早创建时间，小于此时间则超时
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);

        //查询超时订单
        List<Orders> ordersList = ordersMapper.queryTimeoutOrder(Orders.PENDING_PAYMENT,time);

        //取消订单
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("超时未支付");
            orders.setCancelTime(LocalDateTime.now());
            ordersMapper.update(orders);
        }
    }

    /**
     *自动完成超时订单
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void completeDeliveryOrder(){
        //查询前一天还处于配送中的订单
        LocalDateTime time = LocalDateTime.now().minusHours(2);
        List<Orders> ordersList = ordersMapper.queryTimeoutOrder(Orders.DELIVERY_IN_PROGRESS,time);

        //修改订单状态
        for (Orders orders : ordersList) {
            orders.setDeliveryTime(LocalDateTime.now());
            orders.setStatus(Orders.COMPLETED);
            ordersMapper.update(orders);
        }
    }

}
